package com.zxb.rocketmq.springboot_rocketmq_demo.controller;


import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 事务消息  注意这里还有一个监听器 TransactionListenerImpl
 * @author shangtf
 */
@RestController
@RequestMapping("/transMq")
@Slf4j
public class TransactionProducerController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate; //注入Mq

    @RequestMapping("/trans1")
    public void sendTransactionStr()  {
        String[] tags = {"TAGA", "TAGB", "TAGC"};
        for (int i = 0; i < 3; i++) {
            Message<String> message = MessageBuilder.withPayload("事务消息===>" + i).build();
            TransactionSendResult res = rocketMQTemplate.sendMessageInTransaction("transaction-str:" + tags[i], message, i + 1);
            if (res.getLocalTransactionState().equals(LocalTransactionState.COMMIT_MESSAGE) && res.getSendStatus().equals(SendStatus.SEND_OK)) {
                log.info("事物消息发送成功");
            }
            log.info("事物消息发送结果:{}", res);
        }
    }

}
